
package com.fancy.learncenter.common;


import android.util.Base64;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * Created by Hyy on 2016/9/22.
 * 加密算法
 */
public class RSA {


    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;

        keyBytes = Base64.decode(key, Base64.DEFAULT);
        KeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    public static String ecrypt(String content, String pubkey, String input_charset) throws Exception {

        PublicKey publicKey = getPublicKey(pubkey);
        /** 得到Cipher对象来实现对源数据的RSA加密 android特殊处理 */
//        Cipher cipher = Cipher.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] b = content.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return Base64.encodeToString(b1, Base64.DEFAULT);
    }

}
